package com.sgzn.sgpay.service.tcp.model.terminal.request;

import com.sgzn.sgpay.service.tcp.SgTcpProtocolHead;
import com.sgzn.sgpay.service.tcp.util.SgTcpUtil;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;

/**
 * 设置本地账目 请求类
 * @author huangsenguang
 * @version Id: TcpSetLocalBillRequest.java, v 0.1 2018/7/24 13:40 huangsenguang Exp $$
 */
@Data
public class TcpSetLocalBillRequest extends TcpCommonRequest {
    /**
     * 长度
     */
    private String length="12";

    /**
     * 索引
     */
    private String index="01";

    /**
     * 命令
     */
    private String cmd="1D";

    /**
     * Data [0~3]:线下投币或兑币总账
     */
    @NotBlank
    private String data1;

    /**
     * Data [4~7]:退礼总账
     */
    @NotBlank
    private String data2;

    /**
     * Data [8~11]:线上投币或兑币总账
     */
    @NotBlank
    private String data3;

    /**
     * Data[12~15]:出代币总账
     */
    @NotBlank
    private String data4;

    @Override
    public String toString(){
        //根据协议规范重载toString方法
        return beginCode + SgTcpProtocolHead.TCP_SEND_SEPERATOR +
                serialCode + SgTcpProtocolHead.TCP_SEND_SEPERATOR +
                deviceId + SgTcpProtocolHead.TCP_SEND_SEPERATOR +
                commandReq + SgTcpProtocolHead.TCP_SEND_SEPERATOR +
                head + length + index + cmd + getData() +
                getAllCheck(length + index + cmd + getData()) + end + SgTcpProtocolHead.TCP_SEND_SEPERATOR +
                checkSumCode + SgTcpProtocolHead.TCP_SEND_SEPERATOR +
                endCode;
    }

    /**
     * 获取校验码
     * @param needToCheck
     * @return
     */
    private String getAllCheck(String needToCheck) {
        this.setCheck(SgTcpUtil.getToCheck(needToCheck));
        return this.check;
    }

    /**
     * 获取Data 数据
     *   Data [0~3]:线下投币或兑币总账
         Data [4~7]:退礼总账
         Data [8~11]:线上投币或兑币总账
         Data[12~15]:出代币总账
     * @return
     */
    private String getData() {
        return getConvertResult(data1) + getConvertResult(data2) + getConvertResult(data3) +getConvertResult(data4);
    }

    /**
     * 将低位在前的字节数组转换成16进制字符串
     * @param sourceString
     * @return
     */
    private String getConvertResult(String sourceString) {
//        return SgTcpUtil.bytes2HexString(SgTcpUtil.IntToByteArray(Integer.parseInt(sourceString)));
        return SgTcpUtil.intStringToHexString(sourceString, 8);
    }


    public static void main(String[] args){
        TcpSetLocalBillRequest tcpRequest = new TcpSetLocalBillRequest();
        tcpRequest.setDeviceId("10001");
        tcpRequest.setData1("0");
        tcpRequest.setData2("44");
        tcpRequest.setData3("000000");
        tcpRequest.setData4("333333333");
        System.out.println(tcpRequest.toString());
    }
}

